package com.zjgsu.nftplatform.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.Map;

/**
 * @author ahy231
 * @date 2022/3/24 23:12
 * @description
 */
@Component
public class PostUtil {

    @Value("${myurl.go-server}")
    private String server;

    @Value("${go-server.secret}")
    private String secret;

    private final RestTemplate restTemplate;

    public PostUtil(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    private String postMethod(Map<String, String> args, String method) {
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(map, headers);
        map.add("secret", secret);
        args.forEach(map::add);
        byte[] bytes = restTemplate.postForObject("http://" + server + ":8069/" + method, entity, byte[].class);
        Assert.notNull(bytes, "Failed to request go server");
        return new String(bytes, Charset.defaultCharset()).replace("\0", "");
    }

    public String nftPost(Map<String, String> args) {
        return postMethod(args, "nft");
    }

    public String purchasePost(Map<String, String> args) {
        return postMethod(args, "purchase");
    }

    public String accountPost(Map<String, String> args) {
        return postMethod(args, "account");
    }

    public String configPost(Map<String, String> args) {
        return postMethod(args, "config");
    }
}
